package crons;

import helpers.DateHelper;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.models.AutoSiteModel;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import entities.AutoSite;

public class CronAutoSitePageNews extends HttpServlet{
	
	private static final Logger log = Logger.getLogger(CronAutoSitePageNews.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		log.setLevel(Level.FINE);
		
		response.setContentType("text/plain");
		AutoSiteModel autoSiteModel = AutoSiteModel.getInstance();
		List<AutoSite> sites = autoSiteModel.getAll();
		
		
		for (int i = 0; i < sites.size(); i++) {
			AutoSite site = sites.get(i);
			if (site.isGetPage() && !DateHelper.checkGreaterNow(site.getLastestScheduleSitePage(), site.getScheduleSitePage()) && site.getStatus() == 1) {
				DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
				Queue queue = QueueFactory.getDefaultQueue();
				queue.add(TaskOptions.Builder.withUrl("/queue-page-news/" + site.getId()));
				
				log.info("Cron page news success autoSite id: " + site.getId());
				response.getWriter().println("Cron page news success autoSite id: " + site.getId());
			} else {
				log.info("Cron page news unsuccess autoSite id: " + site.getId());
				response.getWriter().println("Cron page news unsuccess autoSite id: " + site.getId());
			}
		}
	}
}